import Dingo.API as api
import random, pdb

__author__ = "Sarah Mount"

class TheSimulation(api.Simulation):
	def __init__(self, graph):
		ether = api.Ether(self)
		sensors = (RandomBlink(graph, ether, i) for i in xrange(30))
		api.Simulation.__init__(self, sensors, graph)

	def run(self):
		super(TheSimulation, self).run()
	
class RandomBlink(api.Sensor):
	def __init__(self, graph, ether, i):
		x = random.randrange(500)
		y = random.randrange(500)
		api.Sensor.__init__(self, graph, "Sensor[%d]" % i, (x, y), api.SensorColor.Red,
			api.Scheduler([BlinkTask(self)], -1), ether)

class BlinkTask(api.Task):
	def __init__(self, sensor):
		api.Task.__init__(self, 0, 0, sensor)

	def task(self):
		node = self.sensor.node
		rgb = random.randrange(1<<24)
		colour = api.SensorColor.FromRGBCombined(rgb)
		node.SetNodeColour(colour)
		sleeptime = random.random()
		api.Sleep(sleeptime)		
		if random.random() < 0.1:
			#pdb.set_trace()
			nodes = node.GetSensorGraph().GetNodes()
			nodes.remove(node)
			if nodes:
				dest = random.choice(nodes)
				if node.GetArcFrom(dest) is None:
					arc = node.AddArcTo(dest, dest.GetNodeColour())
					api.Sleep(1)
					arc.DeleteFromGraph()
